'use strict';
const { Controller } = require('egg')
const path = require('path')
const dayjs = require('dayjs')
const OSS = require('ali-oss')

const clinet = new OSS({
  region: 'oss-cn-shanghai',
  accessKeyId: 'LTAII9ZMYI4fZZqG',
  accessKeySecret: '5SpU9d51M1Q96tCbgtfq1VeWKR6pQS',
  bucket: 'qcms-upload',
})

class BaseController extends Controller {

  // 成功
  success(res) {
    this.ctx.body = {
      code: 200,
      data: res,
    };
  }

  // 失败
  fail(err) {
    this.ctx.body = {
      code: 500,
      error: err,
    };
  }

  // 未找到
  notFound(err) {
    this.ctx.body = {
      code: 404,
      error: err,
    };
  }

  // 上传
  async uploadFile() {
    const { ctx } = this;
    const stream = await ctx.getFileStream();
    const uplaodBasePath = dayjs(new Date().getTime()).format('YYYY-MM-DD');
    const objectKey = `${uplaodBasePath}/${new Date().getTime() + Math.random().toString(36).substr(2) + path.extname(stream.filename).toLocaleLowerCase()}`
    const result = await clinet.putStream(objectKey, stream);
    return result;
  }
}

module.exports = BaseController;
